using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Activa.CoolStorage;
using CodeStory.Core;
using CodeStory.Core.ObjectEntity;
using CodeStory.Core.UI;
using System.Collections.Generic;

namespace CodeStory.WebApplication.Modules.Core.Admin
{
	[NavigationPortlet("CodeStory_Core_Admin_SetUserRole")]
	public partial class SetUserRole : Portlet
	{
		protected override void OnInit(EventArgs e) {
			Load += new EventHandler(SetUserRole_Load);
			cancelButton.Click += new EventHandler(CancelButton_Click);
			okButton.Click += new EventHandler(OKButton_Click);
			base.OnInit(e);
		}

		void OKButton_Click(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			string userid = Request.QueryString["userid"];
			if (string.IsNullOrEmpty(userid)) return;
			UserObject user = UserObject.Read(new Guid(userid));

			CSList<UserInRoleObject> list = UserInRoleObject.List("UserID=@UserID","@UserID",user.UserID);
			list.DeleteAll();
			foreach (ListItem item in rolesCheckBoxList.Items) {
				if (item.Selected) {
					UserInRoleObject u = UserInRoleObject.New();
					u.UserID = user.UserID;
					u.RoleID = new Guid(item.Value);
					u.Save();
				}
			}
			PrivateNavigate();
		}

		void CancelButton_Click(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			PrivateNavigate();
		}

		void SetUserRole_Load(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			if (!IsPostBack) {
				BindRolesList();

				SetUserRoles();
			}
		}

		private void SetUserRoles() {
			string userid = Request.QueryString["userid"];
			if (string.IsNullOrEmpty(userid)) return;
			UserObject user = UserObject.Read(new Guid(userid));

			userNameLabel.Text = user.UserName;
			rolesCheckBoxList.SelectedIndex = -1;
			foreach (RoleObject r in user.Roles) {
				SetCheckBox(r.RoleID);
			}
		}

		private void SetCheckBox(Guid guid) {
			string id = guid.ToString();
			foreach (ListItem item in rolesCheckBoxList.Items) {
				if (id.Equals(item.Value)) {
					item.Selected = true;
					return;
				}
			}
		}

		private void BindRolesList() {
			CSList<RoleObject> list = RoleObject.List();
			rolesCheckBoxList.DataSource = list;
			rolesCheckBoxList.DataTextField = "RoleName";
			rolesCheckBoxList.DataValueField = "RoleID";
			rolesCheckBoxList.DataBind();
		}

		private void PrivateNavigate() {
			Response.Redirect("~/CodeStory_Core_Admin_UserManager.portlet.aspx");
		}
	}
}